<template>
  <div class="flex h-screen bg-gray-50">
    <!-- 错误信息提示 -->
    <ErrorMessage 
      :error="error" 
      @close="clearError" 
    />
    <!-- 左侧边栏 -->
    <div class="w-80 bg-white border-r border-gray-200 flex flex-col">
      <!-- 标题 -->
      <div class="p-6 border-b border-gray-200">
        <h1 class="text-xl font-semibold text-gray-800">中医理疗馆AI助手</h1>
      </div>

      <!-- 新建对话按钮 -->
      <div class="p-4">
        <button 
          @click="handleNewConversation"
          class="w-full btn-primary flex items-center justify-center gap-2"
          :disabled="loading"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
          </svg>
          新建对话
        </button>
      </div>

      <!-- 聊天记录 -->
      <div class="flex-1 overflow-y-auto">
        <div class="px-4 py-2">
          <h3 class="text-sm font-medium text-gray-600 mb-3">聊天记录</h3>
          <div v-if="sessions.length === 0" class="text-center text-gray-500 text-sm py-8">
            暂无聊天记录
          </div>
          <div v-else class="space-y-2">
            <div
              v-for="session in sessions"
              :key="session.session_id"
              @click="selectSession(session)"
              class="p-3 rounded-lg cursor-pointer transition-colors duration-200 hover:bg-gray-50"
              :class="{
                'bg-primary-50 border border-primary-200': currentSession?.session_id === session.session_id
              }"
            >
              <div class="flex items-center justify-between">
                <div class="flex-1 min-w-0">
                  <p class="text-sm font-medium text-gray-800 truncate">
                    {{ session.title }}
                  </p>
                  <p class="text-xs text-gray-500 mt-1">
                    {{ formatSessionDate(session.updated_at) }}
                  </p>
                </div>
                <button
                  @click.stop="deleteSession(session.session_id)"
                  class="text-gray-400 hover:text-red-500 transition-colors duration-200"
                >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 记忆管理 -->
      <div class="p-4 border-t border-gray-200">
        <h3 class="text-sm font-medium text-gray-600 mb-3">记忆管理</h3>
        <div class="space-y-2">
          <button 
            @click="viewMemory"
            class="w-full btn-secondary flex items-center gap-2 text-left"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
            </svg>
            查看记忆
          </button>
          <button 
            @click="clearMemory"
            class="w-full btn-secondary flex items-center gap-2 text-left text-red-600 hover:text-red-700"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
            </svg>
            清空记忆
          </button>
        </div>
      </div>

      <!-- 在线状态 -->
      <div class="p-4 border-t border-gray-200">
        <div class="flex items-center gap-2">
          <div class="w-2 h-2 bg-green-500 rounded-full"></div>
          <span class="text-sm text-gray-600">在线</span>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col">
      <!-- 左侧医生区域 -->
      <div class="flex-1 flex">
        <div class="w-1/3 bg-gradient-to-br from-green-50 to-green-100 flex items-center justify-center p-8">
          <div class="text-center">
            <div class="w-32 h-32 bg-white rounded-full flex items-center justify-center mb-4 shadow-lg border-4 border-green-200">
              <img src="/doctor.svg" alt="中医理疗师" class="w-20 h-20" />
            </div>
            <h3 class="text-lg font-semibold text-gray-800 mb-2">中医理疗师</h3>
            <p class="text-sm text-gray-600">专业的中医理疗咨询</p>
          </div>
        </div>

        <!-- 右侧聊天区域 -->
        <div class="flex-1 bg-white flex flex-col">
          <!-- 聊天消息区域 -->
          <div class="flex-1 overflow-y-auto p-6">
            <!-- 欢迎消息 -->
            <div v-if="conversations.length === 0" class="text-center py-12">
              <h2 class="text-2xl font-bold text-gray-800 mb-2">Hi, 你好</h2>
              <p class="text-gray-600">我是你的AI助手，有什么可以帮助你的吗？</p>
            </div>

            <!-- 对话消息 -->
            <div v-else class="space-y-6">
              <div
                v-for="conversation in conversations"
                :key="conversation.id"
                class="space-y-4"
              >
                <!-- 用户消息 -->
                <MessageBubble
                  :message="conversation.user_input"
                  :timestamp="conversation.timestamp"
                  :is-user="true"
                />

                <!-- AI回复 -->
                <MessageBubble
                  :message="conversation.ai_response"
                  :timestamp="conversation.timestamp"
                  :is-user="false"
                  @copy="handleCopyMessage"
                />
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="flex justify-center py-4">
              <LoadingSpinner text="AI正在思考中..." />
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="border-t border-gray-200 p-4">
            <div class="flex gap-3">
              <input
                v-model="messageInput"
                @keyup.enter="sendMessage"
                type="text"
                placeholder="和AI说点什么..."
                class="flex-1 input-field"
                :disabled="loading"
              />
              <button
                @click="sendMessage"
                :disabled="!messageInput.trim() || loading"
                class="btn-primary px-6"
              >
                发送
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useChatStore } from '../stores/chat'
import ErrorMessage from '../components/ErrorMessage.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import MessageBubble from '../components/MessageBubble.vue'
import { formatDate, getRelativeTime } from '../utils'

export default {
  name: 'ChatView',
  setup() {
    const chatStore = useChatStore()
    const messageInput = ref('')

    const handleNewConversation = async () => {
      await chatStore.createSession()
    }

    const selectSession = async (session) => {
      await chatStore.selectSession(session)
    }

    const deleteSession = async (sessionId) => {
      if (confirm('确定要删除这个会话吗？')) {
        await chatStore.deleteSession(sessionId)
      }
    }

    const sendMessage = async () => {
      if (!messageInput.value.trim() || chatStore.loading) return
      
      const message = messageInput.value.trim()
      messageInput.value = ''
      
      await chatStore.sendMessage(message)
    }

    const viewMemory = () => {
      alert('记忆功能开发中...')
    }

    const clearMemory = () => {
      if (confirm('确定要清空当前对话记忆吗？')) {
        chatStore.clearMemory()
      }
    }

    const clearError = () => {
      chatStore.error = null
    }

    const handleCopyMessage = (message) => {
      // 可以在这里添加复制成功的提示
      console.log('消息已复制:', message)
    }

    const formatSessionDate = (dateString) => {
      return getRelativeTime(dateString)
    }

    onMounted(async () => {
      await chatStore.fetchSessions()
    })

    return {
      // 状态
      messageInput,
      loading: chatStore.loading,
      sessions: chatStore.sessions,
      currentSession: chatStore.currentSession,
      conversations: chatStore.conversations,
      error: chatStore.error,
      
      // 方法
      handleNewConversation,
      selectSession,
      deleteSession,
      sendMessage,
      viewMemory,
      clearMemory,
      clearError,
      handleCopyMessage,
      formatSessionDate
    }
  }
}
</script> 